package org.crazyit.cloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Configuration //要加入这个注解，否则下面的@Bean就不能注入到spring容器里
public class TestController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    @GetMapping("/router")
    public String router(){
        //现在用RestTemplate来调用服务，根据eureka上注册上去的警察局的服务id去调用
        RestTemplate tpl =  getRestTemplate();  //这个RestTemplate已经实现了负载均衡的效果，是因为上面的方法使用了@LoadBalanced注解
        //只是一个地址，请求就发到服务器端去了。
        String json = tpl.getForObject("http://cloud-police/call/33",String.class);
        return json;
    }

    @GetMapping("/list")
    @ResponseBody
    public String serviceCount(){
        List<String> names = discoveryClient.getServices();  //这里是获取服务
        for(String serviceId : names) {
            //这里是获取服务实例。根据实例ID来获取实例
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
            System.out.println(serviceId + ": " + instances.size());
        }
        return "";
    }

}
